import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/widgets/choice_bar.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/module/record/rank_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class RankPage extends StatefulWidget {
  RankPage({Key? key, required this.tag})
      : logic = Get.put(RankLogic(), tag: tag),
        super(key: key);

  final String tag;
  final RankLogic logic;

  @override
  State<RankPage> createState() => _RankPageState();
}

class _RankPageState extends State<RankPage>
    with AutomaticKeepAliveClientMixin {
  late final RankLogic logic = widget.logic;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<RankLogic>(
        tag: widget.tag,
        initState: (state) {
          widget.logic.tag = widget.tag;
          logic.getData();
        },
        builder: (logic) {
          return LoadingWidget<bool>(
            isLoading: logic.isLoading,
            data: false,
            child: () => Container(
              color: Colours.white,
              child: Column(children: [
                widget.tag == "俱乐部" ? Container() : _buildPageChoice(),
                Expanded(
                    child: LoadingWidget<bool>(
                  isLoading: logic.months == null,
                  data: logic.months?.length == 0,
                  child: () => EasyRefresh.builder(
                      controller: logic.refreshController,
                      onRefresh: logic.getData,
                      childBuilder:
                          (BuildContext context, ScrollPhysics physics) {
                        return CustomScrollView(
                          physics: physics,
                          slivers: [
                            SliverToBoxAdapter(child: header()),
                            SliverList(
                                delegate: SliverChildListDelegate(List.generate(
                                    logic.data?.length ?? 0,
                                    (index) =>
                                        content(logic.data?[index], index))))
                          ],
                        );
                      }),
                ))
              ]),
            ),
          );
        });
  }

  Widget _buildPageChoice() {
    return Container(
      padding: const EdgeInsets.only(left: 12, right: 8, top: 5, bottom: 5),
      decoration: const BoxDecoration(
          border:
              Border(bottom: BorderSide(color: Colours.greyEE, width: 0.5))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () => logic.showTypePicker(),
            child: Container(
              key: ValueKey(widget.tag),
              height: 24,
              width: 57,
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 6, right: 2),
              decoration: BoxDecoration(
                  color: Colours.greyF5F7FA,
                  borderRadius: BorderRadius.circular(15)),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    QsText(
                        widget.tag != "篮球"
                            ? logic.sexList[logic.sexIndex]
                            : logic.sexBbList[logic.sexIndex],
                        needCenter: true,
                        fontSize: 12),
                    const SizedBox(width: 4),
                    Padding(
                      padding: const EdgeInsets.only(top: 2),
                      child: Image.asset(
                          width: 8, Utils.getImgPath('down_arrow.png')),
                    )
                  ]),
            ),
          ),
          Container(width: 6),
          Expanded(
              child: ChoiceBar(
                  initialIndex: logic.typeIndex,
                  needScroll: true,
                  items: widget.tag != "篮球" ? logic.typeList : logic.typeBbList,
                  onTap: (i) => logic.setType(i)))
        ],
      ),
    );
  }

  Widget header() {
    return SizedBox(
      height: 38,
      child: Row(
        children: [
          Container(
              padding: const EdgeInsets.only(left: 16),
              child: QsText(widget.tag == "俱乐部" ? "球队" : "国家/地区",
                  fontSize: 13, color: Colours.grey66)),
          const Spacer(),
          Container(
              width: 54,
              alignment: Alignment.center,
              child: QsText("排名变化", fontSize: 13, color: Colours.grey66)),
          // Container(
          //     width: 54,
          //     alignment: Alignment.center,
          //     child: QsText("积分变化",style: Styles.normalSubText(fontSize: 13))),
          GestureDetector(
            onTap: () => logic.showDatePicker(),
            child: Container(
                width: 90,
                alignment: Alignment.center,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    QsText(
                        "${logic.months?[logic.dateIndex].rankMonth!.split(RegExp(r'[0-9]*-')).join()}月积分",
                        fontSize: 13,
                        color: Colours.grey66),
                    const SizedBox(width: 2),
                    Padding(
                      padding: const EdgeInsets.only(top: 2),
                      child: Image.asset(
                          width: 8, Utils.getImgPath('down_arrow.png')),
                    )
                  ],
                )),
          )
        ],
      ),
    );
  }

  Widget content(entity, int index) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        if (widget.tag == '篮球') {
          Get.toNamed(Routes.lqTeamDetail, arguments: entity.teamQxbId);
        } else {
          Get.toNamed(Routes.zqTeamDetail, arguments: entity.teamQxbId);
        }
      },
      child: Container(
        height: 50,
        color: logic.tag != "俱乐部" && index == 0 && logic.typeIndex <= 1
            ? Colours.blueECF2FE
            : null,
        alignment: Alignment.center,
        child: Row(
          children: [
            Container(
                width: 36,
                alignment: Alignment.center,
                child: QsText("${entity.rank ?? "-"}", fontSize: 13)),
            ClipRRect(
              borderRadius: BorderRadius.circular(1),
              child: CachedNetworkImage(
                  width: 24,
                  height: 24,
                  fit: BoxFit.fitWidth,
                  placeholder: (context, url) => Styles.placeholderIcon(),
                  errorWidget: (context, url, error) =>
                      Image.asset(Utils.getImgPath("team_logo.png")),
                  imageUrl: entity.logo ?? ""),
            ).paddingOnly(right: 8),
            ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 120),
              child: QsText(
                entity.nameChs ?? "-",
                fontSize: 13,
                maxLines: 2,
              ),
            ),
            const Spacer(),
            Container(
                width: 54,
                alignment: Alignment.center,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (entity.rankChange != 0 && entity.rankChange != null)
                      Image.asset(
                          width: 7,
                          Utils.getImgPath((entity.rankChange ?? 0) > 0
                              ? "up_arrow_red.png"
                              : "down_arrow_green.png")),
                    QsText(
                      "${entity.rankChange?.abs() ?? "-"}",
                      color: (entity.rankChange ?? 0) != 0
                          ? (entity.rankChange ?? 0) > 0
                              ? Colours.redF13333
                              : Colours.green
                          : Colours.text,
                      fontSize: 13,
                    )
                  ],
                )),
            // Container(
            //     width: 54,
            //     alignment: Alignment.center,
            //     child: Row(
            //       mainAxisSize: MainAxisSize.min,
            //       children: [
            //         if(entity.scoreChange != 0 && entity.scoreChange != null)
            //           Image.asset(Utils.getImgPath((entity.scoreChange ?? 0) > 0?"up_arrow_red.png":"down_arrow_green.png")),
            //         QsText(
            //             "${entity.scoreChange?.abs() ?? "-"}",
            //             style: Styles.normalText(fontSize: 13).copyWith(color: (entity.scoreChange ?? 0) != 0?(entity.scoreChange ?? 0) > 0?Colours.blue2766D6:Colours.green:Colours.text)),
            //       ],
            //     )),
            Container(
                width: 90,
                alignment: Alignment.center,
                child: QsText("${entity.score ?? "-"}", fontSize: 13))
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
